<template>
  <div class="order-review-page">
    <Header />
    <div class="container">
      <div class="order-info-card card">
        <h3 class="card-title">订单信息</h3>
        <p>订单号：{{ order.order_no }}</p>
        <p>下单时间：{{ order.create_time }}</p>
      </div>

      <div class="product-review-card card" v-for="(product, index) in order.products" :key="product.id">
        <h3 class="card-title">评价商品：{{ product.spu_name }}</h3>
        <div class="product-item">
          <img :src="proxy.$buildUrl(product.main_image)" alt="商品图片" class="product-image" />
          <div class="product-details">
            <p class="product-name">{{ product.spu_name }}</p>
            <p class="product-specs">{{ product.sku_name }}</p>
          </div>
        </div>

        <div class="review-section">
          <div class="rating-section">
            <span class="label">商品评分：</span>
            <div class="stars">
              <span v-for="n in 5" :key="n" :class="['star', { filled: n <= product.star_product }]" @click="setRating(index, n)"> ★ </span>
            </div>
          </div>

          <div class="comment-section">
            <span class="label">评价内容：</span>
            <textarea v-model="product.comment_text" placeholder="请输入您的评价内容..." rows="4"></textarea>
          </div>

          <div class="upload-images-section">
            <span class="label">上传图片 (可选)：</span>
            <div class="image-upload-area">
              <el-upload
                v-model:file-list="product.comment_images"
                :action="uploadUrl"
                list-type="picture-card"
                :limit="9"
                :multiple="true"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :before-upload="beforeUpload"
                :on-success="uploadSuccess"
                :auto-upload="true"
                accept=".jpg,.jpeg,.png"
                :headers="uploadHeaders"
                :loading="uploadloading">
                <el-icon><Plus /></el-icon>
              </el-upload>
            </div>
          </div>
        </div>
      </div>

      <div class="overall-review-card card">
        <h3 class="card-title">整体评价</h3>
        <div class="rating-section">
          <span class="label">快递包装：</span>
          <div class="stars">
            <span v-for="n in 5" :key="n" :class="['star', { filled: n <= overallRating.star_package }]" @click="setOverallRating('star_package', n)">
              ★
            </span>
          </div>
          <el-text type="warning" style="margin-left: 10px">{{ overallRating.star_package_desc }}</el-text>
        </div>
        <div class="rating-section">
          <span class="label">物流速度：</span>
          <div class="stars">
            <span
              v-for="n in 5"
              :key="n"
              :class="['star', { filled: n <= overallRating.star_logistics }]"
              @click="setOverallRating('star_logistics', n)">
              ★
            </span>
          </div>
          <el-text type="warning" style="margin-left: 10px">{{ overallRating.star_logistics_desc }}</el-text>
        </div>
        <div class="rating-section">
          <span class="label">配送服务：</span>
          <div class="stars">
            <span
              v-for="n in 5"
              :key="n"
              :class="['star', { filled: n <= overallRating.star_delivery }]"
              @click="setOverallRating('star_delivery', n)">
              ★
            </span>
          </div>
          <el-text type="warning" style="margin-left: 10px">{{ overallRating.star_delivery_desc }}</el-text>
        </div>
      </div>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>

      <div class="actions">
        <button type="button" class="btn primary-btn" @click="submitReview">提交评价</button>
        <button type="button" class="btn secondary-btn" @click="goBack">返回</button>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import Header from '@/components/Header.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useUserStore } from '@/stores/user.js'
  import apiOrder from '@/api/modules/order'

  const route = useRoute()
  const router = useRouter()
  const userStore = useUserStore()
  const { proxy } = getCurrentInstance()

  // 传值方式 router.push(`/order-detail/${order.id}`)
  const orderId = route.params.id ? route.params.id : ''

  const order = ref({})

  const overallRating = ref({
    star_package: 0,
    star_package_desc: '',
    star_logistics: 0,
    star_logistics_desc: '',
    star_delivery: 0,
    star_delivery_desc: '',
  })

  const loadOrderDetail = () => {
    apiOrder.GetOrdersInfo({ id: orderId }).then(async (res) => {
      res.data.products.forEach((item) => {
        item.comment_text = ''
        item.comment_images = []
        item.star_product = 0
        item.star_product_desc = ''
      })
      order.value = res.data
    })
  }

  onMounted(() => {
    loadOrderDetail()
  })

  const setRating = (productIndex, rating) => {
    order.value.products[productIndex].star_product = rating
    order.value.products[productIndex].star_product_desc = getRatingText(rating)
  }

  const setOverallRating = (type, rating) => {
    overallRating.value[type] = rating
    overallRating.value[type + '_desc'] = getRatingText(rating)
  }

  // 获取评分文本
  const getRatingText = (rating) => {
    const texts = ['', '很差', '一般', '满意', '很好', '非常好']
    return texts[rating] || ''
  }

  const submitReview = () => {
    // 验证评价内容
    for (let i = 0; i < order.value.products.length; i++) {
      const product = order.value.products[i]
      if (product.star_product === 0) {
        ElMessage.warning(`请为${product.spu_name}/${product.sku_name}评分`)
        return
      }
    }

    if (overallRating.value.star_package === 0) {
      ElMessage.warning('请为快递包装评分')
      return
    }

    if (overallRating.value.star_logistics === 0) {
      ElMessage.warning('请为物流速度评分')
      return
    }

    if (overallRating.value.star_delivery === 0) {
      ElMessage.warning('请为配送服务评分')
      return
    }

    for (let i = 0; i < order.value.products.length; i++) {
      const fileList = []
      order.value.products[i].comment_images.forEach((item) => {
        fileList.push(item.response ? item.response.data.relativeUrl : item.relativeUrl)
      })
      order.value.products[i].comment_images = fileList
    }

    const saveForm = {
      order_id: orderId,
      commentArray: order.value.products,
      overallRating: overallRating.value,
      comment_nickname: userStore.displayName,
      comment_avatar: userStore.avatarDisplay,
    }
    apiOrder.CommentOrders(saveForm).then(async (res) => {
      ElMessage.success(res.msg)
      router.back()
    })
  }

  const goBack = () => {
    router.back()
  }

  // 附件上传
  const dialogVisible = ref(false)
  const dialogImageUrl = ref('')
  const uploadloading = ref(false)
  const url = '/api/App_Upload/UploadFile?company_id=' + userStore.companyId
  const uploadUrl = proxy.$getBaseURL() + url
  const param_json = ref({})
  const uploadHeaders = { ...proxy.$buildHeaderSign(url, userStore.userInfo, param_json.value) }
  const beforeUpload = (rawFile) => {
    // 上传文件之前的钩子
    if (!uploadUrl) {
      ElMessage.warning('请设置正确的上传地址')
      return false
    }
    const isJPG = rawFile.type.includes('image/')
    const isLt20M = rawFile.size / 1024 / 1024 < 20
    if (!isJPG) {
      ElMessage.warning('只能上传图片格式')
    }
    if (!isLt20M) {
      ElMessage.warning('上传文件大小不能超过 20MB')
    }
    return isJPG && isLt20M
  }
  const uploadSuccess = (res, uploadFile) => {
    // 文件上传成功时的钩子
    console.log('文件上传成功时的钩子', res, uploadFile)
    uploadloading.value = true
    if (res.code == 100) {
      // list-type="picture-card"会自动更新更新fileList
    } else {
      ElMessage.error(res.msg)
    }
  }
  const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
  }
  const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
  }
</script>

<style scoped>
  .order-review-page {
    padding: 20px 0;
    min-height: calc(100vh - 130px); /* 减去Header和Footer的高度 */
  }

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0;
  }

  .page-title {
    font-size: 28px;
    color: #333;
    text-align: center;
    margin-bottom: 30px;
    font-weight: bold;
    position: relative;
    padding-bottom: 10px;
  }

  .page-title::after {
    content: '';
    position: absolute;
    left: 50%;
    bottom: 0;
    transform: translateX(-50%);
    width: 60px;
    height: 3px;
    background-color: #961d13; /* 品牌色 */
    border-radius: 2px;
  }

  .card {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    margin-bottom: 20px;
    padding: 25px;
  }

  .card-title {
    font-size: 20px;
    color: #333;
    margin-bottom: 20px;
    font-weight: 600;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
  }

  .order-info-card p {
    font-size: 15px;
    color: #555;
    line-height: 1.8;
  }

  .product-item {
    display: flex;
    align-items: center;
    padding: 15px 0;
    border-bottom: 1px dashed #eee;
    margin-bottom: 15px;
  }

  .product-item:last-child {
    border-bottom: none;
  }

  .product-image {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
    margin-right: 15px;
    border: 1px solid #f0f0f0;
  }

  .product-details {
    flex-grow: 1;
  }

  .product-name {
    font-size: 16px;
    color: #333;
    font-weight: 500;
    margin-bottom: 5px;
  }

  .product-specs {
    font-size: 13px;
    color: #999;
  }

  .review-section {
    padding-top: 15px;
  }

  .review-section .label {
    font-size: 15px;
    color: #666;
    margin-bottom: 10px;
    display: block;
  }

  .rating-section {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
  }

  .rating-section .stars {
    display: flex;
    gap: 5px;
  }

  .rating-section .star {
    font-size: 24px;
    color: #ccc;
    cursor: pointer;
    transition: color 0.2s ease;
  }

  .rating-section .star.filled {
    color: #ffc107; /* Gold color for filled stars */
  }

  .comment-section textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    min-height: 100px;
    resize: vertical;
    box-sizing: border-box; /* Ensure padding and border are included in the element's total width and height */
  }

  .upload-images-section {
    margin-top: 15px;
  }

  .image-upload-area {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 10px;
  }

  .upload-button {
    width: 80px;
    height: 80px;
    border: 2px dashed #ccc;
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 36px;
    color: #ccc;
    cursor: pointer;
    transition: border-color 0.2s ease, color 0.2s ease;
  }

  .upload-button:hover {
    border-color: #961d13;
    color: #961d13;
  }

  .uploaded-image {
    position: relative;
    width: 80px;
    height: 80px;
    border-radius: 4px;
    overflow: hidden;
    border: 1px solid #eee;
  }

  .uploaded-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .delete-image {
    position: absolute;
    top: 2px;
    right: 2px;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    cursor: pointer;
  }

  /* Actions */
  .actions {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 20px;
    margin-top: 30px;
  }

  .btn {
    padding: 12px 30px;
    border: none;
    border-radius: 25px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-weight: 500;
  }

  .primary-btn {
    background-color: #961d13; /* 品牌色 */
    color: #fff;
  }

  .primary-btn:hover {
    background-color: #7a170f;
    box-shadow: 0 4px 12px rgba(150, 29, 19, 0.3);
  }

  .secondary-btn {
    background-color: #52a58a; /* 辅助色 */
    color: #fff;
  }

  .secondary-btn:hover {
    background-color: #459a7e;
    box-shadow: 0 4px 12px rgba(82, 165, 138, 0.3);
  }

  /* Responsive Design */
  @media (max-width: 768px) {
    .container {
      padding: 0 15px;
    }

    .page-title {
      font-size: 24px;
      margin-bottom: 25px;
    }

    .card {
      padding: 20px;
      margin-bottom: 15px;
    }

    .card-title {
      font-size: 18px;
      margin-bottom: 15px;
    }

    .product-item {
      flex-wrap: wrap;
      justify-content: space-between;
      padding: 12px 0;
    }

    .product-image {
      width: 70px;
      height: 70px;
      margin-right: 10px;
    }

    .product-details {
      flex-basis: calc(100% - 85px); /* Adjust based on image width + margin */
      margin-bottom: 10px;
    }

    .review-section .label {
      font-size: 14px;
    }

    .rating-section .star {
      font-size: 20px;
    }

    .comment-section textarea {
      font-size: 13px;
    }

    .upload-button,
    .uploaded-image {
      width: 70px;
      height: 70px;
    }

    .btn {
      padding: 10px 25px;
      font-size: 15px;
    }

    .actions {
      gap: 15px;
      margin-top: 25px;
    }
  }

  @media (max-width: 480px) {
    .page-title {
      font-size: 22px;
      margin-bottom: 20px;
    }

    .card {
      padding: 15px;
    }

    .card-title {
      font-size: 16px;
      margin-bottom: 12px;
    }

    .order-info-card p {
      font-size: 14px;
    }

    .product-image {
      width: 50px;
      height: 50px;
      margin-right: 8px;
    }

    .product-details {
      flex-basis: calc(100% - 60px);
    }

    .product-name {
      font-size: 15px;
    }

    .product-specs {
      font-size: 12px;
    }

    .review-section .label {
      font-size: 13px;
    }

    .rating-section .star {
      font-size: 18px;
    }

    .comment-section textarea {
      font-size: 12px;
    }

    .upload-button,
    .uploaded-image {
      width: 60px;
      height: 60px;
    }

    .upload-button span {
      font-size: 30px;
    }

    .btn {
      max-width: 250px;
    }
  }
</style>
